<?php
/**
 * Created By virus_cms
 * Desc: 图片上传类
 * Author: Virus
 * Date: 2020/3/2
 * Time: 11:26
 */

namespace app\common\lib;


use think\facade\Filesystem;

class ImageUploadHandle
{
    // 只允许以下后缀的图片文件
    protected $allowed_ext = ["png", "jpg", "gif", 'jpeg'];

    /**
     * @param $file
     * @param $folder
     * @param bool $fileas 默认为false，保存到public目录下的指定目录格式下；为true，保存到public下的指定目录下
     * @return bool|string
     */
    public function save($file, $folder, $fileas = false)
    {
        if ($file) {
            $extension = strtolower($file->extension());
            // 如果上传的不是图片终止操作
            if (!in_array($extension, $this->allowed_ext)) {
                return false;
            }
            try {
                $savename = $fileas == false
                    ? Filesystem::disk('public')->putFile($folder, $file)
                    : Filesystem::disk(
                        'public'
                    )
                        ->putFileAs($folder.'/'.date('Ymd'), $file, $file->getOriginalName());
            } catch (\Exception $e) {
                return $e->getMessage();
            }
            if ($savename) {
                // TP6中获取图片路径的方法
                $path = Filesystem::getDiskConfig('public', 'url').'/'.str_replace('\\', '/', $savename);

                return $path;
            }
        }

        return false;
    }
}